package me.zhengjie.rest;

import io.swagger.annotations.Api;
import lombok.RequiredArgsConstructor;
import me.zhengjie.annotation.AnonymousAccess;
import me.zhengjie.config.FileProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.http.HttpHeaders;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;


import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.nio.file.Path;
import java.nio.file.Paths;

import java.io.IOException;
import java.nio.file.Files;
import java.util.*;

@RestController
@RequiredArgsConstructor
@RequestMapping("api/fileUpLoad")
@Api(tags = "工具：文件上传")
public class FileUpLoadUtilsController {

    @Value("${file.windows.path}")
    private String uploadDir;

    private final FileProperties properties;
    private final List<String> allowedContentTypes = Arrays.asList("image/jpeg", "image/png", "image/gif");

    @PostMapping("/upload")
    @AnonymousAccess
    public ResponseEntity<Object> uploadFile(@RequestParam("file") MultipartFile file) {
        try {
            FileProperties.ElPath path = properties.getPath();
            // 确保上传目录存在
            String uploadDirP = path.getPath().replace("\\","/");
            Path uploadPath = Paths.get(uploadDirP);
            if (!Files.exists(uploadPath)) {
                Files.createDirectories(uploadPath);
            }
            if (!allowedContentTypes.contains(file.getContentType())) {
                return ResponseEntity.badRequest().body("只允许上传图片文件");
            }

            // 生成唯一文件名
            String fileName = UUID.randomUUID() + "_" + file.getOriginalFilename();

            // 保存文件
            Path filePath = uploadPath.resolve(fileName);
            file.transferTo(filePath.toFile());
            Map res = new HashMap<String, Object>();
            res.put("id", fileName);
            return ResponseEntity.ok(res);
        } catch (IOException e) {
            return ResponseEntity.badRequest().body("文件上传失败: " + e.getMessage());
        }
    }

    @PostMapping("/uploadAllFile")
    @AnonymousAccess
    public ResponseEntity<Object> uploadAllFile(@RequestParam("file") MultipartFile file) {
        try {
            FileProperties.ElPath path = properties.getPath();
            // 确保上传目录存在
            String uploadDirP = path.getPath().replace("\\","/");
            Path uploadPath = Paths.get(uploadDirP);
            if (!Files.exists(uploadPath)) {
                Files.createDirectories(uploadPath);
            }
            // 生成唯一文件名
            String fileName = UUID.randomUUID() + "_" + file.getOriginalFilename();

            // 保存文件
            Path filePath = uploadPath.resolve(fileName);
            file.transferTo(filePath.toFile());
            Map res = new HashMap<String, Object>();
            res.put("id", fileName);
            return ResponseEntity.ok(res);
        } catch (IOException e) {
            return ResponseEntity.badRequest().body("文件上传失败: " + e.getMessage());
        }
    }


//    @GetMapping("/images/{filename:.+}")
//    @AnonymousAccess
//    public void imageLook (HttpServletResponse response, @PathVariable String filename) {
//
//        File file = new File(uploadDir + "/" + filename);
//        byte[] bytes = new byte[1024];
//        try (
//            OutputStream os = response.getOutputStream();
//            FileInputStream fis = new FileInputStream(file)){
//            while ((fis.read(bytes)) != -1) {
//                os.write(bytes);
//                os.flush();
//            }
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//    }

    @GetMapping("/images/{filename:.+}")
    @AnonymousAccess
    public ResponseEntity<InputStreamResource> imageLook (HttpServletResponse response, @PathVariable String filename)  throws IOException{

        // 假设图片存储在项目的images目录下
        File imgFile = new File(uploadDir + "/" + filename);

        return ResponseEntity
                .ok()
                .contentType(MediaType.IMAGE_JPEG) // 根据实际图片类型调整
                .body(new InputStreamResource(new FileInputStream(imgFile)));
    }

    private String determineContentType(String filename) {
        // 根据文件扩展名确定内容类型
        String extension = filename.substring(filename.lastIndexOf(".") + 1).toLowerCase();
        switch (extension) {
            case "jpg":
            case "jpeg":
                return MediaType.IMAGE_JPEG_VALUE;
            case "png":
                return MediaType.IMAGE_PNG_VALUE;
            case "gif":
                return MediaType.IMAGE_GIF_VALUE;
            default:
                return MediaType.APPLICATION_OCTET_STREAM_VALUE;
        }
    }



}
